package com.xishu.controller;

import com.xishu.annotation.valid.MethodValidator;
import com.xishu.cash.QfPayClient;
import com.xishu.config.Constant;
import com.xishu.entity.order.Order;
import com.xishu.service.order.callback.OrderCallBackService;
import com.xishu.entity.shop.Shop;
import com.xishu.response.VerifyUtil;
import com.xishu.service.order.base.OrderService;
import com.xishu.service.ShopService;
import com.xishu.util.AES;
import com.xishu.util.ServletUtil;
import com.xishu.util.Tools;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class QfController implements Tools {
    private static Logger logger = LoggerFactory.getLogger(QrCodeController.class);

    @PostMapping(value = ("/ssl/qf/webhook"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(mustLogin = false)
    public String webhook(@RequestBody String payload) throws Exception {
        String sigHeader = ServletUtil.getRequest().getHeader("X-QF-SIGN");
        JSONObject notifyJson = JSONObject.fromObject(payload);
        String out_trade_no = notifyJson.getString("out_trade_no");
        String[] split = out_trade_no.split(Constant.SEPERATOR_KEY);

        VerifyUtil.verify(() -> isNotEmpty(split));
        VerifyUtil.verify(() -> split.length == 2);
        Long shopId = Long.valueOf(split[0]);
        Long orderId = Long.valueOf(split[1]);

        Shop shop = ShopService.getInstance().findShopById(shopId);
        VerifyUtil.verify(() -> isNotEmpty(shop.getQfCode()));
        VerifyUtil.verify(() -> isNotEmpty(shop.getQfKey()));
        VerifyUtil.verify(() -> isNotEmpty(shop.getQfSid()));

        QfPayClient qfPayClient = new QfPayClient(AES.decrypt(shop.getQfCode()), AES.decrypt(shop.getQfKey()), shop.getQfSid());
        boolean verify = qfPayClient.verify(payload, sigHeader);

        if (!verify) {
            logger.info("verify failed");
            return "FAILED";
        }

        String notify_type = notifyJson.getString("notify_type");
        if (!equals(notify_type, "Payment")) {
            logger.info("not payment");
            return "FAILED";
        }

        Order order = new Order();
        order.setShopId(shopId);
        order.setId(orderId);

        Order orderInDb = OrderService.getInstance().findOrderCanFlagDelete(order);

        //处理订单
        OrderCallBackService.getInstance().orderCallback(orderInDb);
        logger.info("return success");
        return "SUCCESS";
    }
}
